package com.wechat.app.ui.screens.discover

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.remember
import com.wechat.app.R
import com.wechat.app.ui.navigation.navigateBack

data class Moment(
    val author: String,
    val avatar: String? = null,
    val content: String,
    val images: List<String> = emptyList(),
    val time: String,
    val likes: List<String> = emptyList(),
    val comments: List<Comment> = emptyList()
)

data class Comment(
    val author: String,
    val content: String,
    val replyTo: String? = null
)

object MockMoments {
    val moments = listOf(
        Moment(
            author = "张三",
            content = "今天天气真好！",
            images = listOf("img_1", "img_2"),
            time = "2小时前",
            likes = listOf("李四", "王五"),
            comments = listOf(
                Comment("李四", "确实不错！"),
                Comment("王五", "我也觉得")
            )
        ),
        Moment(
            author = "李四",
            content = "分享一首好听的歌",
            images = listOf("img_3"),
            time = "5小时前",
            likes = listOf("张三", "赵六"),
            comments = listOf(
                Comment("张三", "好听！")
            )
        ),
        Moment(
            author = "王五",
            content = "周末去爬山了，风景很美",
            images = listOf("img_4", "img_5", "img_6"),
            time = "昨天",
            likes = listOf("张三", "李四", "赵六"),
            comments = listOf(
                Comment("张三", "羡慕！"),
                Comment("李四", "下次一起去")
            )
        ),
        Moment(
            author = "赵六",
            content = "美食分享",
            images = listOf("img_7", "img_8", "img_9", "img_1"),
            time = "3天前",
            likes = listOf("张三", "李四", "王五"),
            comments = listOf(
                Comment("张三", "看起来很好吃！"),
                Comment("李四", "在哪里？")
            )
        )
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MomentsScreen() {
    val moments = remember { MockMoments.moments }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("朋友圈") },
                navigationIcon = {
                    IconButton(onClick = { navigateBack() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = { /* TODO: Camera */ }) {
                        Icon(Icons.Default.PhotoCamera, contentDescription = "拍照")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent
                )
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Header with user info
            item {
                MomentsHeader()
            }
            
            // Moments list
            items(
                items = moments,
                key = { it.author + it.time }
            ) { moment ->
                MomentItem(moment = moment)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}

@Composable
fun MomentsHeader() {
    val context = LocalContext.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(200.dp)
    ) {
        // Background image
        Image(
            painter = painterResource(id = getImageResourceId("img_1")),
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )
        
        // User avatar and name at bottom
        Row(
            modifier = Modifier
                .align(Alignment.BottomStart)
                .padding(16.dp),
            verticalAlignment = Alignment.Bottom
        ) {
            Surface(
                color = MaterialTheme.colorScheme.surface,
                shape = CircleShape,
                modifier = Modifier.size(64.dp)
            ) {
                Image(
                    painter = painterResource(id = getImageResourceId("img_1")),
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }
            Spacer(modifier = Modifier.width(12.dp))
            Text(
                text = "Sean",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                color = Color.White,
                modifier = Modifier.padding(bottom = 8.dp)
            )
        }
    }
}

@Composable
fun MomentItem(moment: Moment) {
    Surface(
        color = MaterialTheme.colorScheme.surface,
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // Author info
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    color = MaterialTheme.colorScheme.surfaceVariant,
                    shape = CircleShape,
                    modifier = Modifier.size(40.dp)
                ) {
                    Image(
                        painter = painterResource(id = getImageResourceId("img_${(moment.author.hashCode() % 9) + 1}")),
                        contentDescription = null,
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.Crop
                    )
                }
                Spacer(modifier = Modifier.width(12.dp))
                Column {
                    Text(
                        text = moment.author,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = moment.time,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // Content
            if (moment.content.isNotEmpty()) {
                Text(
                    text = moment.content,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // Images
            if (moment.images.isNotEmpty()) {
                val imageCount = moment.images.size
                when {
                    imageCount == 1 -> {
                        // Single large image
                        Image(
                            painter = painterResource(id = getImageResourceId(moment.images[0])),
                            contentDescription = null,
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(200.dp)
                                .clip(RoundedCornerShape(8.dp)),
                            contentScale = ContentScale.Crop
                        )
                    }
                    imageCount <= 3 -> {
                        // 2-3 images in a row
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            moment.images.take(3).forEach { imageName ->
                                Image(
                                    painter = painterResource(id = getImageResourceId(imageName)),
                                    contentDescription = null,
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                        .clip(RoundedCornerShape(4.dp)),
                                    contentScale = ContentScale.Crop
                                )
                            }
                        }
                    }
                    else -> {
                        // Grid layout for 4+ images
                        val rows = (imageCount + 2) / 3
                        Column(
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            repeat(rows) { row ->
                                Row(
                                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                                ) {
                                    moment.images.drop(row * 3).take(3).forEach { imageName ->
                                        Image(
                                            painter = painterResource(id = getImageResourceId(imageName)),
                                            contentDescription = null,
                                            modifier = Modifier
                                                .weight(1f)
                                                .aspectRatio(1f)
                                                .clip(RoundedCornerShape(4.dp)),
                                            contentScale = ContentScale.Crop
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // Likes and comments
            if (moment.likes.isNotEmpty() || moment.comments.isNotEmpty()) {
                Surface(
                    color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f),
                    shape = RoundedCornerShape(4.dp),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        // Likes
                        if (moment.likes.isNotEmpty()) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Favorite,
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp),
                                    tint = MaterialTheme.colorScheme.error
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = moment.likes.joinToString("、"),
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                            if (moment.comments.isNotEmpty()) {
                                Spacer(modifier = Modifier.height(8.dp))
                            }
                        }
                        
                        // Comments
                        moment.comments.forEach { comment ->
                            Text(
                                text = "${comment.author}: ${comment.content}",
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(vertical = 2.dp)
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // Action buttons
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                TextButton(onClick = { /* TODO: Like */ }) {
                    Icon(
                        imageVector = Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("赞")
                }
                TextButton(onClick = { /* TODO: Comment */ }) {
                    Icon(
                        imageVector = Icons.Default.Comment,
                        contentDescription = "评论",
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("评论")
                }
            }
        }
    }
}

/**
 * 根据图片名称获取资源 ID
 */
fun getImageResourceId(imageName: String): Int {
    return when (imageName) {
        "img_1" -> R.drawable.img_1
        "img_2" -> R.drawable.img_2
        "img_3" -> R.drawable.img_3
        "img_4" -> R.drawable.img_4
        "img_5" -> R.drawable.img_5
        "img_6" -> R.drawable.img_6
        "img_7" -> R.drawable.img_7
        "img_8" -> R.drawable.img_8
        "img_9" -> R.drawable.img_9
        else -> R.drawable.img_1 // 默认图片
    }
}

